package fragments;

import helper.GetFBUserPhotoHelper;
import helper.HttpHelper;

import java.util.Calendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.matchcalendar.R;

import activities.MatchResultActivity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import dataFormat.CalendarTextData;
import dataFormat.FBUser;

public class MatchResultFragment extends ScheduleControlFragment {
	private List<CalendarTextData> myScheduleDataList;
	private MatchResultActivity myActivity;

	public MatchResultFragment(boolean isAddScheduleEnabled, Calendar weekCal,
			List<CalendarTextData> myScheduleDataList) {
		super(isAddScheduleEnabled, weekCal);
		this.myScheduleDataList = myScheduleDataList;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		
		try {
			myActivity = (MatchResultActivity)getActivity();
			for (CalendarTextData calTextData: myScheduleDataList)
				addCalendarText(calTextData, null, null, Gravity.LEFT);
			if (myActivity.isHaveGetData()) {
				for (int i=0; i<myActivity.getMatchCalDataList().size(); i++) {
					CalendarTextData data = myActivity.getMatchCalDataList().get(i);
					
					addCalendarText(data, new MatchScheduleTextClick(
							myActivity.getMatchResultJsonArr().getJSONObject(i), data, getWeekCal()), null, Gravity.CENTER);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return view;
    }
	
	public class MatchScheduleTextClick implements TextView.OnClickListener {
		private JSONObject jsonObj;
		private CalendarTextData calData;
		private Calendar theWeekCal = Calendar.getInstance();
		
		public MatchScheduleTextClick(JSONObject jsonObj, CalendarTextData calData, Calendar weekCal) {
			this.jsonObj = jsonObj;
			this.calData = calData;
			theWeekCal.set(weekCal.get(Calendar.YEAR), weekCal.get(Calendar.MONTH),
					weekCal.get(Calendar.DATE));
		}

		@Override
		public void onClick(View v) {
			try {
				View dialogView = View.inflate(myActivity, R.layout.custom_show_up_situation_view, null);
				TextView textViewNoCollision =
						(TextView) dialogView.findViewById(R.id.textViewNoCollision);
				TextView textViewCollisionLow =
						(TextView) dialogView.findViewById(R.id.textViewCollisionLow);
				TextView textViewCollisionMedium =
						(TextView) dialogView.findViewById(R.id.textViewCollisionMedium);
				TextView textViewCollisionHigh =
						(TextView) dialogView.findViewById(R.id.textViewCollisionHigh);
				LinearLayout linearLayoutNoCollision = (LinearLayout)
						dialogView.findViewById(R.id.linearLayoutNoCollision);
				LinearLayout linearLayoutCollisionLow = (LinearLayout)
						dialogView.findViewById(R.id.linearLayoutCollisionLow);
				LinearLayout linearLayoutCollisionMedium = (LinearLayout)
						dialogView.findViewById(R.id.linearLayoutCollisionMedium);
				LinearLayout linearLayoutCollisionHigh = (LinearLayout)
						dialogView.findViewById(R.id.linearLayoutCollisionHigh);
				JSONArray jsonArrNoCollision = jsonObj.getJSONArray("noCollision");
				JSONArray jsonArrLowCollision = jsonObj.getJSONArray("lowCollision");
				JSONArray jsonArrMidCollision = jsonObj.getJSONArray("midCollision");
				JSONArray jsonArrHighCollision = jsonObj.getJSONArray("highCollision");
				
				if (jsonArrNoCollision.length() != 0)
					textViewNoCollision.setVisibility(View.VISIBLE);
				if (jsonArrLowCollision.length() != 0)
					textViewCollisionLow.setVisibility(View.VISIBLE);
				if (jsonArrMidCollision.length() != 0)
					textViewCollisionMedium.setVisibility(View.VISIBLE);
				if (jsonArrHighCollision.length() != 0)
					textViewCollisionHigh.setVisibility(View.VISIBLE);
				addNamePhotos(linearLayoutNoCollision, jsonArrNoCollision);
				addNamePhotos(linearLayoutCollisionLow, jsonArrLowCollision);
				addNamePhotos(linearLayoutCollisionMedium, jsonArrMidCollision);
				addNamePhotos(linearLayoutCollisionHigh, jsonArrHighCollision);
				new AlertDialog.Builder(myActivity)
				.setTitle("出席資訊")
				.setView(dialogView)
				.setNegativeButton("取消", null)
				.setPositiveButton("發送揪團訊息", new ButtonSendMessageClick())
				.show();
			} catch (JSONException e) {
				e.printStackTrace();
			}	
		}
		
		private void addNamePhotos(LinearLayout layout, JSONArray jsonArr) {
			try {
				for (int i=0; i<jsonArr.length(); i++) {
					JSONObject friendJsonObj = jsonArr.getJSONObject(i);
					FBUser friend = myActivity.getIdFriendsMap().get(friendJsonObj.getString("id")); 
					TextView namePhoto = new TextView(myActivity);
					Drawable defaultIcon = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
					
					namePhoto.setCompoundDrawablesWithIntrinsicBounds(null, defaultIcon, null, null);
					namePhoto.setGravity(Gravity.CENTER_HORIZONTAL);
					namePhoto.setText(friend.getName() + "\n" + friendJsonObj.getString("collisionTime"));
					if (friend.getPhoto() == null)
						new GetFriendPhotos(namePhoto).execute(friend);
					else {
						Drawable drawableBitmap = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(
								friend.getPhoto(), defaultIcon.getIntrinsicWidth(), defaultIcon.getIntrinsicHeight(), true));
						
						namePhoto.setCompoundDrawablesWithIntrinsicBounds(null, drawableBitmap, null, null);
					}
					layout.addView(namePhoto);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		private class GetFriendPhotos extends GetFBUserPhotoHelper {
			private TextView namePhoto;
			
			public GetFriendPhotos(TextView namePhoto) {
				this.namePhoto = namePhoto;
			}

			@Override
			protected void onPostExecute(FBUser fbUser) {
				Drawable defaultIcon = getResources().getDrawable(R.drawable.com_facebook_profile_default_icon);
				Drawable drawableBitmap = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(
						fbUser.getPhoto(), defaultIcon.getIntrinsicWidth(), defaultIcon.getIntrinsicHeight(), true));
				
				namePhoto.setCompoundDrawablesWithIntrinsicBounds(null, drawableBitmap, null, null);
			}
		}

		private class ButtonSendMessageClick implements DialogInterface.OnClickListener {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				new PostInsertActivity().execute();
			}
			
			private class PostInsertActivity extends AsyncTask<Void, Void, Void> {
				private ProgressDialog proDialog;
				
				@Override
				protected void onPreExecute() {
					proDialog = ProgressDialog.show(myActivity, "發送訊息", "正在發送揪團訊息...");
					proDialog.setCancelable(false);
				}

				@Override
				protected Void doInBackground(Void... params) {
					try {
						JSONObject reqJsonObj = new JSONObject();
						JSONArray friendsJsonArr = new JSONArray();
						Bundle bundleFromPrevious = myActivity.getBundleFromPrevious();
						
						theWeekCal.add(Calendar.DATE, calData.getDay());
						reqJsonObj.put("id", myActivity.getIntent().getExtras().getString("myFBID"));
						reqJsonObj.put("activityName", bundleFromPrevious.get("activityName"));
						reqJsonObj.put("icon", bundleFromPrevious.get("icon"));
						reqJsonObj.put("activityPlace", bundleFromPrevious.get("activityPlace"));
						reqJsonObj.put("date", theWeekCal.get(Calendar.YEAR) + "-" +
						(theWeekCal.get(Calendar.MONTH) + 1) + "-" + theWeekCal.get(Calendar.DATE));
						reqJsonObj.put("day", calData.getDay());
						reqJsonObj.put("startTime", calData.getStartHour() + ":" + calData.getStartMinute());
						reqJsonObj.put("overTime", calData.getOverHour() + ":" + calData.getOverMinute());
						reqJsonObj.put("activityPs", bundleFromPrevious.get("activityPs"));
						for (String id: myActivity.getIdFriendsMap().keySet())
							friendsJsonArr.put(id);
						reqJsonObj.put("friends", friendsJsonArr);
						HttpHelper.executePost("http://iculture.twgg.org/activity/insertActivity.php", reqJsonObj.toString());
					} catch (JSONException e) {
						e.printStackTrace();
					}
					return null;
				}
				
				@Override
				protected void onPostExecute(Void result) {
					proDialog.cancel();
					myActivity.setResult(FragmentActivity.RESULT_OK);
					myActivity.finish();
				}
			}
		}
	}
	
	@Override
	protected void onHeightChange() {
		List<MatchResultFragment> scheduleList = myActivity.getScheduleList();
		ViewPager matchSchedulePager = myActivity.getMatchSchedulePager();
		
		for (MatchResultFragment matchResultFragment: scheduleList) {
			matchResultFragment.setNowHeight(getNowHeight());
			matchResultFragment.setUnitHeight(getUnitHeight());
		}
		if (matchSchedulePager.getCurrentItem() - 1 >= 0)
			scheduleList.get(matchSchedulePager.getCurrentItem() - 1).resetHeight();
		if (matchSchedulePager.getCurrentItem() + 1 < scheduleList.size())
			scheduleList.get(matchSchedulePager.getCurrentItem() + 1).resetHeight();
	}
}
